package ch.zbw.pra.sysventory.ui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class AgentMainFrame extends JFrame implements KeyListener {

	private static AgentMainFrame mainFrame;

	private static final long serialVersionUID = 927297332308021609L;
	private JFrame agentMainFrame;
	private JPanel ipPanel;
	private JLabel ipLabel;
	private JTextField ipTextField;
	private InfoLabel infoLabel;
	private DetailLabel detailLabel;
	private boolean enterKeyPressed = false;

	private AgentMainFrame() {
		agentMainFrame = new JFrame("sysventory - AGENT");
		agentMainFrame.setSize(400, 150);
		agentMainFrame.setResizable(false);
		agentMainFrame.setLocationRelativeTo(null);
		ipLabel = new JLabel("Bitte IP-Adresse vom Server eingeben - Bsp: 10.0.4.127");
		ipTextField = new JTextField();
		ipTextField.setPreferredSize(new Dimension(150, 25));
		ipTextField.setHorizontalAlignment(JTextField.CENTER);
		ipTextField.addKeyListener(this);
		infoLabel = new InfoLabel();
		detailLabel = new DetailLabel();
		ipPanel = new JPanel(new FlowLayout());
		ipPanel.add(ipLabel);
		ipPanel.add(ipTextField);
		ipPanel.add(infoLabel.getInfoLabel());
		ipPanel.add(detailLabel.getDetailLabel());
		agentMainFrame.add(ipPanel);

		agentMainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		agentMainFrame.setVisible(true);

	}

	public String getIPAdressFromTextField() {
		String ipAddress = "";
		ipAddress = ipTextField.getText();
		ipTextField.setBackground(Color.RED);
		while (!enterKeyPressed) {
			ipTextField.setBackground(Color.RED);
		}
		ipTextField.setBackground(Color.GREEN);
		return ipAddress;

	}

	public boolean validateIPAddress(String ipAddress) {
		String[] parts = ipAddress.split("\\.");
		if (parts.length != 4) {
			return false;
		}
		for (String s : parts) {
			int i = Integer.parseInt(s);
			if ((i < 0) || (i > 255)) {
				return false;
			}
		}
		return true;
	}

	public void keyPressed(KeyEvent e) {
		if (e.getKeyCode() == KeyEvent.VK_ENTER) {
			enterKeyPressed = true;
		}

	}

	public void keyReleased(KeyEvent arg0) {
	}

	public void keyTyped(KeyEvent arg0) {
	}

	public static AgentMainFrame getInstance() {
		if (mainFrame == null) {
			mainFrame = new AgentMainFrame();
		}
		return mainFrame;
	}
}
